package com.uduemc.security.core.authentication;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class SmsAuthenticationProvider implements AuthenticationProvider {

	private UserDetailsService userDetailsService;

	/**
	 * 执行身份认证的逻辑
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		SmsAuthenticationToken smsAuthenticationToken = (SmsAuthenticationToken) authentication;
		UserDetails loadUserByUsername = userDetailsService
				.loadUserByUsername((String) smsAuthenticationToken.getPrincipal());

		if (loadUserByUsername == null) {
			throw new InternalAuthenticationServiceException("无法获取用户信息");
		}
		
		SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(loadUserByUsername, loadUserByUsername.getAuthorities());
		authenticationResult.setDetails(smsAuthenticationToken.getDetails());
		
		return authenticationResult;
	}

	/**
	 * AuthenticationManager 根据此方法选取 哪个实现 AuthenticationProvider 接口的类作来进行操作
	 * 
	 * 判断 authentication 是不是 SmsAuthenticationToken 这个类型
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return SmsAuthenticationToken.class.isAssignableFrom(authentication);
	}

	public UserDetailsService getUserDetailsService() {
		return userDetailsService;
	}

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	
}
